//
//  QBUserAccount.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/22.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

class QBUserAccount: NSObject,NSCoding {
    // string	用于调用access_token，接口获取授权后的access token
    var access_token: String?
    
    // reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb0000000966017f3'
    // access_token的生命周期，单位是秒数
    // 基本数据类型作为属性不能为可选，使用一个默认值
    var expires_in: NSTimeInterval = 0 {
        
        didSet {
            // 当KVC给expire_in赋值完成后将expire_in转成NSDate
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期时间，expires_in转成系统的NSDate,expires_in是Double不好来判断过期时间，转成NSDate比较好判断过期时间
    var expiresDate: NSDate?
    
    // 当前授权用户的UID。
    var uid: String?
    
    // MARK: - 用户信息
    /// 用户名称
    var screen_name: String?
    
    /// 用户头像地址
    var avatar_large: String?
    
    /*
    {
        "access_token" = "2.00RumxQC0jtGeu7c08f6517bfj42ED";
        "expires_in" = 157679999;
        "remind_in" = 157679999;
        uid = 2082936393;
    }
    */
    /// 使用KVC赋值转模型
    init(dict:[String: AnyObject]) {
        
        // 没有在super.init()之前给属性赋值，属性需要定义为可选
        super.init()
        
        // 使用KVC赋值
        setValuesForKeysWithDictionary(dict)
    }
    
    /// 字典的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
        print("forUndefinedKey:\(key)")
    }
    
    // 对象打印
    override var description: String {
        // 只读属性
        get {
            let keys = ["access_token","expires_in","expiresDate","uid"]
            
            return dictionaryWithValuesForKeys(keys).description
        }
    }
    
    // MARK: - 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate,forKey: "expiresDate")
        aCoder.encodeObject(uid,forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}

//extension QBUserAccount:NSCoding {
//    
//    func encodeWithCoder(aCoder: NSCoder) {
//        
//        
//    }
//    // NSCoding 的这个 init?(coder aDecoder: NSCoder) 是需要为指定构造函数,在extension 构造函数只能是便利构造函数
//    init?(coder aDecoder: NSCoder) {
//        
//        
//    }
//}
